package com.shengqi.xinnongren.work.ui.home.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpFragment;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ArrayUtil;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.widgets.LooperTextView;
import com.shengqi.xinnongren.work.common.MyWebViewActivity;
import com.shengqi.xinnongren.work.model.HttpRespond;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.goods.activities.GoodsDetailsActivity;
import com.shengqi.xinnongren.work.ui.home.activities.MainActivity;
import com.shengqi.xinnongren.work.ui.home.activities.NewsListActivity;
import com.shengqi.xinnongren.work.ui.home.activities.SearchActivity;
import com.shengqi.xinnongren.work.ui.home.activities.SpecialSaleActivity;
import com.shengqi.xinnongren.work.ui.home.model.BannerBean;
import com.shengqi.xinnongren.work.ui.home.model.GoodsBean;
import com.shengqi.xinnongren.work.ui.home.model.HomePage1Bean;
import com.shengqi.xinnongren.work.ui.home.model.NewsDetailsBean;
import com.shengqi.xinnongren.work.ui.home.model.RecommendGoodsBean;
import com.shengqi.xinnongren.work.ui.home.presenter.HomePage1Presenter;
import com.shengqi.xinnongren.work.ui.home.view.HomePage1View;
import com.shengqi.xinnongren.work.ui.user.activities.MessageActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomePage1Fragment extends BaseMvpFragment<HomePage1View, HomePage1Presenter> implements HomePage1View {

    private static final long TIME_BANNER_LOOPER = 4000;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.ll_net_error)
    LinearLayout mLlError;
    @BindView(R.id.iv_message)
    ImageView iv_message;
    @BindView(R.id.rv_hot_key)
    RecyclerView mRvHotKey;
    @BindView(R.id.cb_banner)
    ConvenientBanner<String> mBanner;
    @BindView(R.id.lt_view)
    LooperTextView mLooperTextView;

    //广告
    @BindViews({R.id.iv_adv_2_1, R.id.iv_adv_2_2, R.id.iv_adv_4_1, R.id.iv_adv_4_2, R.id.iv_adv_4_3, R.id.iv_adv_4_4, R.id.iv_adv_1_1})
    List<ImageView> mImageViewList;
    @BindView(R.id.ll_adv2)
    LinearLayout ll_adv2;
    @BindView(R.id.ll_adv4)
    LinearLayout ll_adv4;

    @BindView(R.id.ll_special_sale)
    LinearLayout mLLSpecialSale;
    @BindView(R.id.rv_special_sale)
    RecyclerView mRvSpecialSale;
    @BindView(R.id.rv_new_recommend)
    RecyclerView mRvNewRecommend;

    private List<String> mHotKeyList;
    private List<BannerBean> mBannerList;
    private List<GoodsBean> mGoodsList;
    private List<RecommendGoodsBean> mRecommendList;

    private HotKeyAdapter mHotKeyAdapter;
    private SpecialSaleAdapter mSpecialSaleAdapter;
    private RecommendGoodsAdapter mRecommendGoodsAdapter;

    private int pageIndex = 0;
    private boolean isLoginState;

    public HomePage1Fragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isLoginState = UserManager.getInstance().isLogin();
    }

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_home_page1;
    }

    @Override
    protected HomePage1Presenter createPresenter() {
        return new HomePage1Presenter();
    }

    @Override
    protected void lazyLoadData() {
        getPageData();
    }

    private void getPageData() {
        getPresenter().getData();
        getGoodList(false);
    }

    @Override
    protected void initView() {
        mHotKeyList = new ArrayList<>();
        mBannerList = new ArrayList<>();
        mGoodsList = new ArrayList<>();
        mRecommendList = new ArrayList<>();

        mHotKeyAdapter = new HotKeyAdapter(R.layout.item_hot_key, mHotKeyList);
        mRvHotKey.setAdapter(mHotKeyAdapter);
        mRvHotKey.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        //banner图的比例 2:1
        mBanner.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = mBanner.getLayoutParams();
                layoutParams.height = (int) (mBanner.getWidth() / 2.5f);
                mBanner.setLayoutParams(layoutParams);
                mBanner.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        //两个小广告比例 1:0.8
        ImageView ivHalfAd = mImageViewList.get(0);
        ivHalfAd.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = ivHalfAd.getLayoutParams();
                layoutParams.height = (int) (ivHalfAd.getWidth() * .8f);
                ivHalfAd.setLayoutParams(layoutParams);
                mImageViewList.get(1).setLayoutParams(layoutParams);
                ivHalfAd.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        //四个小广告比例 1:1
        ImageView ivLittleAd = mImageViewList.get(2);
        ivLittleAd.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = ivLittleAd.getLayoutParams();
                layoutParams.height = ivLittleAd.getWidth();
                for (int i = 2; i < 6; i++) {
                    mImageViewList.get(i).setLayoutParams(layoutParams);
                }
                ivLittleAd.setLayoutParams(layoutParams);
                ivLittleAd.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        //通栏广告比例 4:1
        final ImageView ivTongLanAd = mImageViewList.get(6);
        ivTongLanAd.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = ivTongLanAd.getLayoutParams();
                layoutParams.height = ivTongLanAd.getWidth() / 4;
                ivTongLanAd.setLayoutParams(layoutParams);
                ivTongLanAd.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        mSpecialSaleAdapter = new SpecialSaleAdapter();
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mRvSpecialSale);
        mRvSpecialSale.setAdapter(mSpecialSaleAdapter);
        mRvSpecialSale.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });


        mRecommendGoodsAdapter = new RecommendGoodsAdapter();
        mRvNewRecommend.setAdapter(mRecommendGoodsAdapter);
        mRvNewRecommend.addItemDecoration(Global.genRecyclerViewItemDecoration(getActivity(), 10, Color.parseColor("#f9f9f9")));
        mRvNewRecommend.setLayoutManager(new GridLayoutManager(getActivity(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

    }

    @Override
    protected void initData() {
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            getPageData();
        }).setOnLoadMoreListener(refreshLayout ->
                getGoodList(true)
        );
    }

    /**
     * 获取商品列表
     */
    public void getGoodList(boolean isLoadMore) {
        if (isLoadMore)
            pageIndex++;
        else
            pageIndex = 0;
        getPresenter().getRecommendGoodsList(pageIndex);
    }


    @Override
    public void showHomeData(HttpRespond<HomePage1Bean> respond) {
        iv_message.setVisibility(respond.data.getIsHaveMessage() == 1 ? View.VISIBLE : View.GONE);
        setHotKey(respond.data.getKeyWords());
        setBanner(respond.data.getBannerList());
        setTips(respond.data.getContentList());
        setAdvertising(respond.data.getAdvertisingMap());
        setSpecialSale(respond.data.getSpecialCom());
    }


    @Override
    public void showLoginInvalid() {
        Global.reLogin(getContext());
    }

    @Override
    public void showRecommendGoodsList(HttpRespond<List<RecommendGoodsBean>> respond) {
        resetRefreshLayout();
        if (pageIndex == 0)
            mRecommendList.clear();
        if (respond.data != null && respond.data.size() > 0) {
            mRecommendList.addAll(respond.data);
        }
        mRecommendGoodsAdapter.notifyDataSetChanged();
    }

    private void resetRefreshLayout() {
        mRefreshLayout.finishRefresh().finishLoadMore();
    }


    /**
     * 搜索推荐词
     *
     * @param keyWords
     */
    private void setHotKey(List<String> keyWords) {
        mHotKeyList.clear();
        mHotKeyList.addAll(keyWords);
        mHotKeyAdapter.notifyDataSetChanged();
    }

    /**
     * Banner图
     *
     * @param bannerList
     */
    void setBanner(List<BannerBean> bannerList) {
        mBannerList.clear();
        mBannerList.addAll(bannerList);
        mBanner.setPages(() -> new NetImageLoadHolder(), ArrayUtil.listConvertToStringList(mBannerList, BannerBean::getPicUrl));

        mBanner.setOnItemClickListener(position -> handlerClickEvent(bannerList.get(position).getType(), bannerList.get(position).getValue()));
        mBanner.startTurning(TIME_BANNER_LOOPER);
    }

    /**
     * 微头条
     *
     * @param microList
     */
    void setTips(List<NewsDetailsBean> microList) {
        mLooperTextView.setTipList(ArrayUtil.listConvertToStringList(microList, bean -> bean.getTitle()));
    }

    /**
     * 七张广告位
     *
     * @param bean
     */
    void setAdvertising(HomePage1Bean.AdvertisingMapBean bean) {
        List<BannerBean> oneAdvertising = bean.getOneAdvertising();
        List<BannerBean> twoAdvertising = bean.getTwoAdvertising();
        List<BannerBean> fourAdvertising = bean.getFourAdvertising();

        if (twoAdvertising.size() > 0) {
            ll_adv2.setVisibility(View.VISIBLE);
            ImageUtils.showImage(getContext(), checkIsNull(twoAdvertising.get(0)), mImageViewList.get(0));
            if (!TextUtils.isEmpty(checkIsNull(twoAdvertising.get(0)))) {
                mImageViewList.get(0).setOnClickListener(v -> handlerClickEvent(twoAdvertising.get(0).getType(), twoAdvertising.get(0).getValue()));
            }

            if (twoAdvertising.size() > 1) {
                ImageUtils.showImage(getContext(), checkIsNull(twoAdvertising.get(1)), mImageViewList.get(1));
                if (!TextUtils.isEmpty(checkIsNull(twoAdvertising.get(1)))) {
                    mImageViewList.get(1).setOnClickListener(v -> handlerClickEvent(twoAdvertising.get(1).getType(), twoAdvertising.get(1).getValue()));
                }
            }
        } else
            ll_adv2.setVisibility(View.GONE);

        if (fourAdvertising.size() > 0) {
            ll_adv4.setVisibility(View.VISIBLE);
            ImageUtils.showImage(getContext(), checkIsNull(fourAdvertising.get(0)), mImageViewList.get(2));
            if (!TextUtils.isEmpty(checkIsNull(fourAdvertising.get(0)))) {
                mImageViewList.get(2).setOnClickListener(v -> handlerClickEvent(fourAdvertising.get(0).getType(), fourAdvertising.get(0).getValue()));
            }

            if (fourAdvertising.size() > 1) {
                ImageUtils.showImage(getContext(), checkIsNull(fourAdvertising.get(1)), mImageViewList.get(3));
                if (!TextUtils.isEmpty(checkIsNull(fourAdvertising.get(1)))) {
                    mImageViewList.get(3).setOnClickListener(v -> handlerClickEvent(fourAdvertising.get(1).getType(), fourAdvertising.get(1).getValue()));
                }
            }

            if (fourAdvertising.size() > 2) {
                ImageUtils.showImage(getContext(), checkIsNull(fourAdvertising.get(2)), mImageViewList.get(4));
                if (!TextUtils.isEmpty(checkIsNull(fourAdvertising.get(2)))) {
                    mImageViewList.get(4).setOnClickListener(v -> handlerClickEvent(fourAdvertising.get(2).getType(), fourAdvertising.get(2).getValue()));
                }
            }
            if (fourAdvertising.size() > 3) {
                ImageUtils.showImage(getContext(), checkIsNull(fourAdvertising.get(3)), mImageViewList.get(5));
                if (!TextUtils.isEmpty(checkIsNull(fourAdvertising.get(3)))) {
                    mImageViewList.get(5).setOnClickListener(v -> handlerClickEvent(fourAdvertising.get(3).getType(), fourAdvertising.get(3).getValue()));
                }
            }
        } else
            ll_adv4.setVisibility(View.GONE);

        if (oneAdvertising.size() > 0) {
            mImageViewList.get(6).setVisibility(View.VISIBLE);
            ImageUtils.showImage(getContext(), checkIsNull(oneAdvertising.get(0)), mImageViewList.get(6));
            if (!TextUtils.isEmpty(checkIsNull(oneAdvertising.get(0)))) {
                mImageViewList.get(6).setOnClickListener(v -> handlerClickEvent(oneAdvertising.get(0).getType(), oneAdvertising.get(0).getValue()));
            }
        } else
            mImageViewList.get(6).setVisibility(View.GONE);
    }

    private String checkIsNull(BannerBean bean) {
        return bean == null ? "" : bean.getPicUrl();
    }

    /**
     * 今日特价
     *
     * @param specialCom
     */
    void setSpecialSale(List<GoodsBean> specialCom) {
        mGoodsList.clear();
        mGoodsList.addAll(specialCom);
        mSpecialSaleAdapter.notifyDataSetChanged();
    }


    /**
     * banner 广告位点击跳转
     *
     * @param type type:0二级分类， 1商品详情， 2H5页面, 3搜索关键字
     * @param val
     */
    private void handlerClickEvent(int type, String val) {
        if (val == null) return;
        switch (type) {
            case 0:
                if (val.contains(",")) {
                    String[] split = val.split(",");
                    ((MainActivity) getActivity()).checkSubClass(split[0], split[1]);
                } else
                    ((MainActivity) getActivity()).checkClass(val);

                break;
            case 1:
                GoodsDetailsActivity.start(getContext(), val);
                break;
            case 2:
                startActivity(MyWebViewActivity.getIntent(getActivity(), "", val));
                break;
            case 3:
                SearchActivity.start(getActivity(), val);
                break;
        }
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void hideLoadingView() {

    }

    @Override
    public void onNetworkError() {
        resetRefreshLayout();
        mLlError.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.tv_get_data)
    void tv_get_data() {
        mLlError.setVisibility(View.GONE);
        getPageData();
    }


    @OnClick({R.id.lt_view, R.id.tv_news_more})
    void gotoNewsList() {
        startActivity(new Intent(getActivity(), NewsListActivity.class));
    }

    @Override
    public void onPause() {
        super.onPause();
        mBanner.stopTurning();
    }

    @Override
    public void onResume() {
        super.onResume();
        mBanner.startTurning(TIME_BANNER_LOOPER);
        if (isLoginState != UserManager.getInstance().isLogin()) {
            isLoginState = UserManager.getInstance().isLogin();
            getPageData();
        }
    }

    /**
     * 消息
     */
    @OnClick(R.id.fl_message)
    void fl_message() {
        if (Global.checkLogin(getContext()))
            startActivity(new Intent(getActivity(), MessageActivity.class));
    }

    //搜索
    @OnClick(R.id.ll_search)
    void iv_search() {
        SearchActivity.start(getActivity(), "");
    }


    //今日特价
    @OnClick(R.id.ll_special_sale)
    void ll_special_sale() {
        startActivity(new Intent(getActivity(), SpecialSaleActivity.class));
    }


    public static class NetImageLoadHolder implements Holder<String> {
        private ImageView image_lv;

        //可以是一个布局也可以是一个Imageview
        @Override
        public ImageView createView(Context context) {
            image_lv = new ImageView(context);
            image_lv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return image_lv;

        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(context).load(data).apply(new RequestOptions().placeholder(R.mipmap.img_place_holder)).into(image_lv);
        }
    }

    /**
     * 搜索推荐词适配器
     */
    class HotKeyAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public HotKeyAdapter(int layoutResId, @Nullable List<String> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.item_name, item);
            helper.itemView.setOnClickListener(v -> SearchActivity.start(getContext(), item));
        }
    }


    /**
     * 今日特价适配器
     */
    class SpecialSaleAdapter extends RecyclerView.Adapter<SpecialSaleAdapter.Holder> {
        @NonNull
        @Override
        public SpecialSaleAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(getLayoutInflater().inflate(R.layout.item_special_goods_list, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull SpecialSaleAdapter.Holder holder, int position) {
            GoodsBean goodsBean = mGoodsList.get(position);
            holder.item_isNew.setVisibility(goodsBean.getIsNew() == 1 ? View.VISIBLE : View.GONE);
            ImageUtils.showImage(getActivity(), goodsBean.getMainPic(), holder.item_pic);
            holder.item_name.setText(goodsBean.getComName());
            holder.item_description.setText(goodsBean.getPhrase());
            if (TextUtils.isEmpty(goodsBean.getOriginPlace()))
                holder.tv_original_place.setVisibility(View.GONE);
            else
                holder.tv_original_place.setVisibility(View.VISIBLE);
            holder.tv_original_place.setText(goodsBean.getOriginPlace());
            holder.item_discount_price.setText(String.format("￥%s", goodsBean.getPrice()));
            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(getContext(), goodsBean.getComId()));
            holder.item_car.setOnClickListener(v -> Global.showSpecificationDialog(getActivity(), goodsBean.getComId()));
        }

        @Override
        public int getItemCount() {
            return mGoodsList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_name)
            TextView item_name;
            @BindView(R.id.item_description)
            TextView item_description;
            @BindView(R.id.tv_original_place)
            TextView tv_original_place;
            @BindView(R.id.item_discount_price)
            TextView item_discount_price;
            @BindView(R.id.item_car)
            TextView item_car;


            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /**
     * 新品推荐适配器
     */
    class RecommendGoodsAdapter extends RecyclerView.Adapter<RecommendGoodsAdapter.Holder> {

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_recommend_goods_list, parent, false));
            holder.item_pic.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewGroup.LayoutParams layoutParams = holder.item_pic.getLayoutParams();
                    layoutParams.height = holder.item_pic.getWidth();
                    holder.item_pic.setLayoutParams(layoutParams);
                    holder.item_pic.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
            return holder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull RecommendGoodsAdapter.Holder holder, int position) {

            RecommendGoodsBean bean = mRecommendList.get(position);

            holder.item_isNew.setVisibility(bean.getIsNew() == 1 ? View.VISIBLE : View.GONE);

            ImageUtils.showImage(getActivity(), bean.getMainPic(), holder.item_pic);
            holder.item_name.setText(bean.getComName());
            holder.item_description.setText(bean.getPhrase());
            if (TextUtils.isEmpty(bean.getOriginPlace()))
                holder.tv_original_place.setVisibility(View.GONE);
            else
                holder.tv_original_place.setVisibility(View.VISIBLE);
            holder.tv_original_place.setText(bean.getOriginPlace());
            holder.item_discount_price.setText(String.format("￥%s", bean.getPrice()));
            holder.item_unit.setText(String.format("/%s", bean.getUnitName()));

            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(getContext(), bean.getComId()));
            holder.item_car.setOnClickListener(v -> Global.showSpecificationDialog(getActivity(), bean.getComId()));
        }

        @Override
        public int getItemCount() {
            return mRecommendList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_name)
            TextView item_name;
            @BindView(R.id.item_description)
            TextView item_description;
            @BindView(R.id.tv_origin_place)
            TextView tv_original_place;
            @BindView(R.id.item_discount_price)
            TextView item_discount_price;
            @BindView(R.id.item_unit)
            TextView item_unit;
            @BindView(R.id.item_car)
            ImageView item_car;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

}
